package com.atguigu.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.cloud.entity.Account;
import com.atguigu.cloud.service.AccountService;
import com.atguigu.cloud.mapper.AccountMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author fafa
* @description 针对表【t_account】的数据库操作Service实现
* @createDate 2024-06-26 21:50:41
*/
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account>
    implements AccountService{

    @Resource
    private AccountMapper accountMapper;


    @Override
    public boolean decrease(Long userId, Long money) {
        //模拟超时
        //myTimeOut();
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Account::getUserId,userId);

        Account account = accountMapper.selectOne(queryWrapper);
        if(account == null){
            return false;
        }
        if(account.getResidue() < money){
            return false;
        }
        account.setResidue((int) (account.getResidue() - money));
        account.setUsed((int) (account.getUsed() + money));

        accountMapper.updateById(account);


        return true;
    }

    private static void myTimeOut()
    {
        try { TimeUnit.SECONDS.sleep(65); } catch (InterruptedException e) { e.printStackTrace(); }
    }
}




